﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPITest.Models.Database;

namespace WebAPITest.Service
{
    public class UserService:IUserService
    {
        //定义数据库上下文
        private readonly WebEnterpriseIIContext _db;
        
        //构造注入
        public UserService(WebEnterpriseIIContext db)
        {
            _db = _db;
        }

        /// <summary>
        /// 根据用户名 从数据库获取用户
        /// </summary>
        /// <returns>用户名</returns>
        public User GetNameByUserName(string username)
        {
            return _db.Users.FirstOrDefault(x => x.UserName == username);

        }
        /// <summary>
        /// 根据用户名判断用户是否存在
        /// </summary>
        /// <param name="username"></param>
        /// <returns>是或非</returns>
        public bool TfUserName(string username)
        {
            return _db.Users.Any(x => x.UserName == username);
        }
        /// <summary>
        /// 注册 添加新用户
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="Email"></param>
        /// <param name="NickName"></param>
        /// <param name="Password"></param>
        /// <returns>用户ID</returns>
        public int Reg(string UserName,string Email,string NickName,string Password)
        {
            var user = new User()
            {
                UserName = UserName,
                Email =Email,
                NickName = NickName,
                Password = Password,
                CreateTime = DateTime.Now,
                Salt = 0,
                UserLevel = 1,
            };
            //上下文.表名.操作方法(需要插入的数据对象)
            _db.Users.Add(user);
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return 1;
            }
            return 0;
            
        }
    }
}
